package wang.jinggo.util;




import wang.jinggo.exception.ValidationException;

import java.util.function.Consumer;

/**
 * @author wangyj
 * @description
 * @create 2017-07-04 14:36
 **/
public class ValidatorUtil {
    private ValidationException.Warns warns = ValidationException.Warns.init();

    public static void validate(Consumer<ValidatorUtil> proc) {
        ValidatorUtil validator = new ValidatorUtil();
        proc.accept(validator);
        validator.verify();
    }

    public ValidatorUtil verify() {
        if (hasWarn())
            throw new ValidationException(warns);
        return clear();
    }

    public boolean hasWarn() {
        return warns.nonEmpty();
    }

    public ValidatorUtil clear() {
        warns.list().clear();
        return this;
    }

    public ValidatorUtil verify(boolean valid, String message) {
        return check(valid, message).verify();
    }

    public ValidatorUtil check(boolean valid, String message) {
        if (!valid)
            warns.add(message);
        return this;
    }

    public ValidatorUtil checkField(boolean valid, String field, String message) {
        if (!valid)
            warns.add(field, message);
        return this;
    }

    public ValidatorUtil verifyField(boolean valid, String field, String message) {
        return checkField(valid, field, message).verify();
    }
}
